import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons'
import { App, Col, Form, Input, Modal, Row, Select, UploadFile } from 'antd'
import Upload, { RcFile } from 'antd/es/upload'
import cs from 'classnames'
import { Dispatch, SetStateAction, useEffect, useMemo, useRef, useState } from 'react'

import { Violation } from '@/api/interface'
import arrowNext from '@/assets/arrow-next.png'
import arrowPre from '@/assets/arrow-pre.png'
import del from '@/assets/delete.png'
import SignatureCanvas from '@/components/Signature'
import UploadFileCom from '@/components/UploadFile'

import styles from '../styles/index.module.less'

const { TextArea } = Input

const SignatureKey = {
  'Witness/Violator': { ar: 'مخالف/شاهد', en: 'Witness/Violator' },
  writer: { ar: 'أمين السر', en: 'Writer' },
  translator: { ar: 'مترجم', en: 'Translator' },
  investigator: { ar: 'المحقق', en: 'Investigator' },
  investigator_2: { ar: 'المحقق 2', en: 'Investigator 2' },
  investigator_3: { ar: 'المحقق 3', en: 'Investigator 3' },
}

interface Props {
  t: any
  lang: string
  cancel: () => void
  setSetup: Dispatch<SetStateAction<number>>
  violation: Partial<Violation>
  setViolation: Dispatch<SetStateAction<Partial<Violation>>>
}

function InvestigationDetails({ t, lang, cancel, setSetup, violation, setViolation }: Props) {
  const [form] = Form.useForm()
  const { modal, message } = App.useApp()

  const [isModalOpen, setIsModalOpen] = useState(false)

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const [eid, setEid] = useState('')

  const [signaturesKey, setSignaturesKey] = useState(eid + '' + new Date().getTime())

  const [investigationDetails, setInvestigationDetails] = useState([...violation.details])

  const activeIndex = useMemo(
    () => investigationDetails.findIndex((item) => item.eid === eid),
    [investigationDetails, eid]
  )

  const signatureText = () => {
    const roleKey = investigationDetails[activeIndex]?.role
    const enumRole = [
      { key: 'VIOLATOR', value: { en: 'Violator Signature', ar: 'توقيع المخالف' } },
      { key: 'WITNESS', value: { en: 'Witness Signature', ar: 'توقيع الشاهد' } },
      { key: 'SUSPECT', value: { en: 'Suspect Signature', ar: 'توقيع المشتبه به' } },
      { key: 'WHISTLEBLOWER', value: { en: 'Whistleblower Signature', ar: 'توقيع المبلغ' } },
    ]
    return enumRole.find((item) => item.key === roleKey)?.value[lang === 'en-US' ? 'en' : 'ar']
  }

  useEffect(() => {
    const data = JSON.parse(JSON.stringify(investigationDetails))
    data.forEach((item) => {
      item.attachment ??= []
      item.questions ??= []
    })
    setInvestigationDetails(data)
    setSignaturesKey(eid + '' + new Date().getTime())
    // if (violation.eid) {
    //   const detail = violation.details.find((item) => item.eid === violation.eid)
    //   setEid(violation.eid)
    //   form.setFieldsValue({
    //     violator: violation.eid,
    //     violatorName: detail?.name ?? '',
    //     violatorEmiratesID: violation.eid,
    //     signature: detail?.signature ?? '',
    //     questions: detail?.questions,
    //   })
    // } else {
    setEid(violation.details[0].eid)
    form.setFieldsValue({
      violator: violation.details[0].eid,
      violatorName: violation.details[0].name,
      violatorEmiratesID: violation.details[0].eid,
      nationalityValue: violation.details[0].nationalityValue,
      mobile: violation.details[0].mobile,
      questions: violation.details[0].questions,
    })
    // }
  }, [])

  const FormLabel = ({ title, required = true }: { title: string; required?: boolean }) => {
    return (
      <span className={styles['form-item-label']}>
        {title}
        {required && <span className={styles['form-item-label-required']}>*</span>}
      </span>
    )
  }

  const changeQuestions = (val, key, index) => {
    const data = JSON.parse(JSON.stringify(investigationDetails))
    data[activeIndex].questions[index] ??= { answer: '', question: '', attachment: [] }
    data[activeIndex].questions[index][key] = val
    // clear signature
    if (data[activeIndex].signature || data[activeIndex].signatures?.length) {
      data[activeIndex].signature = ''
      data[activeIndex].signatures = []
      setSignaturesKey(eid + '' + new Date().getTime())
    }
    setInvestigationDetails(data)
  }

  const attachmentValue = () => {
    const attachment = investigationDetails[activeIndex]?.attachment
    return attachment?.length ? attachment : []
  }

  const questionsAttachmentValue = (index) => {
    const questions = investigationDetails[activeIndex]?.questions
    return questions.length ? questions[index]?.attachment ?? [] : []
  }

  const uploadRef = useRef(null)
  const onFile = (files, type, questionIndex) => {
    const data = JSON.parse(JSON.stringify(investigationDetails))
    if (activeIndex == -1) return
    // clear signature
    if (files.length > 0 && (data[activeIndex].signature || data[activeIndex].signatures?.length)) {
      data[activeIndex].signature = ''
      data[activeIndex].signatures = []
      setSignaturesKey(eid + '' + new Date().getTime())
    }

    // Exceeds single maximum length
    if (files?.length > 5) return message.warning(t['form.details.attachments.length.warning'])

    // attachment（单个 attachment）
    if (type === 'attachment') {
      data[activeIndex].attachment ??= []
      const filesLength = data[activeIndex].attachment?.length || 0
      const remainingSlots = 10 - filesLength
      if (files.length > remainingSlots)
        return message.warning(t['form.details.attachments.maxLength.warning'])
      files.forEach((file) => {
        data[activeIndex].attachment.push({
          uid: file.path,
          name: file.name,
          status: 'done',
          url: 'custom://' + file.path,
          path: file.path,
        })
      })
    }

    // questions.attachment (questions 里面的 attachment 数组)
    if (type === 'questions') {
      data[activeIndex].questions[questionIndex] ??= { answer: '', question: '', attachment: [] }
      const filesLength = data[activeIndex].questions[questionIndex].attachment?.length || 0
      const remainingSlots = 10 - filesLength
      if (files.length > remainingSlots)
        return message.warning(t['form.details.attachments.maxLength.warning'])
      files.forEach((file) => {
        data[activeIndex].questions[questionIndex].attachment.push({
          uid: file.path,
          name: file.name,
          status: 'done',
          url: 'custom://' + file.path,
          path: file.path,
        })
      })
    }
    setInvestigationDetails(data)
  }

  const FileUpload = ({
    fileList,
    type,
    questionIndex,
  }: {
    fileList: any[]
    type: string
    questionIndex?: number
  }) => {
    const [previewOpen, setPreviewOpen] = useState(false)
    const [previewImage, setPreviewImage] = useState('')
    const [previewTitle, setPreviewTitle] = useState('')

    const getBase64 = (file: RcFile): Promise<string> =>
      new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result as string)
        reader.onerror = (error) => reject(error)
      })

    const handlePreview = async (file: UploadFile) => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj as RcFile)
      }
      setPreviewImage(file.url || (file.preview as string))
      setPreviewOpen(true)
      setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1))
    }

    const removeFile = (file) => {
      const data = JSON.parse(JSON.stringify(investigationDetails))
      if (activeIndex == -1) return
      // clear signature
      if (file && (data[activeIndex].signature || data[activeIndex].signatures?.length)) {
        data[activeIndex].signature = ''
        data[activeIndex].signatures = []
        setSignaturesKey(eid + '' + new Date().getTime())
      }

      // 删除单个 attachment
      if (type === 'attachment') {
        data[activeIndex].attachment = data[activeIndex].attachment?.filter(
          (item) => item.uid !== file.uid
        )
      }

      // 删除 questions 里面的 attachment
      if (type === 'questions') {
        data[activeIndex].questions[questionIndex].attachment = data[activeIndex].questions[
          questionIndex
        ].attachment?.filter((item) => item.uid !== file.uid)
      }
      setInvestigationDetails(data)
    }

    const UploadButton = () => {
      return (
        <div
          className={styles['upload-button']}
          onClick={(e) => {
            e.stopPropagation()
            uploadRef.current.open(type, questionIndex)
          }}
        >
          <PlusOutlined />
          <div style={{ marginTop: 8 }}>{t['form.details.attachments.upload']}</div>
        </div>
      )
    }

    return (
      <>
        <Upload
          listType="picture-card"
          customRequest={() => {}}
          fileList={fileList}
          onPreview={handlePreview}
          onRemove={removeFile}
        >
          {fileList.length >= 10 ? null : <UploadButton />}
        </Upload>
        <Modal
          open={previewOpen}
          title={previewTitle}
          footer={null}
          onCancel={() => setPreviewOpen(false)}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    )
  }

  const removeQuestion = (remove, name) => {
    const data = JSON.parse(JSON.stringify(investigationDetails))
    const pieceData = data[activeIndex].questions[name]

    const handleRemoval = () => {
      if (data[activeIndex].signature || data[activeIndex].signatures?.length) {
        data[activeIndex].signature = ''
        data[activeIndex].signatures = []
        setSignaturesKey(eid + '' + new Date().getTime())
      }
      remove(name)
      data[activeIndex].questions.splice(name, 1)
      setInvestigationDetails(data)
    }

    const shouldConfirm = pieceData?.answer || pieceData?.question || pieceData?.attachment.length

    const confirmationOptions = {
      title: t['form.confirm.title.del'],
      icon: <ExclamationCircleFilled style={{ color: '#FF7D00' }} />,
      className: cs(styles['custom-modal'], lang === 'en-US' ? '' : styles['custom-modal-rtl']),
      content: t['form.confirm.content.del'],
      okText: t['form.button.del'],
      closable: true,
      okButtonProps: { danger: true },
      cancelText: t['form.button.cancel'],
      keyboard: false,
      onOk() {
        handleRemoval()
      },
    }

    if (shouldConfirm) modal.confirm(confirmationOptions)
    else handleRemoval()
  }

  const changeViolator = (value) => {
    setEid(value)
    setSignaturesKey(eid + '' + new Date().getTime())

    const violator: Violation['details'][number] =
      investigationDetails.find((item) => item.eid === value) ?? {}
    const index = investigationDetails.findIndex((item) => item.eid === value)

    // set form content
    form.setFieldsValue({
      violatorName: violator.name,
      violatorEmiratesID: violator.eid,
      questions: investigationDetails[index].questions,
    })
  }

  /* signatures */
  const signaturesValue = (key) => {
    const signatures = investigationDetails[activeIndex]?.signatures
    return signatures ? signatures.find((v) => v.key === key)?.value ?? '' : ''
  }

  const signatureList = () => {
    const extractedKeys = Object.keys(SignatureKey).filter(
      (key) =>
        key === 'Witness/Violator' || (violation[key] !== null && violation[key] !== undefined)
    )
    return extractedKeys
  }

  const changeSignature = (value, key: string) => {
    if (!value) setSignaturesKey(eid + '' + new Date().getTime())

    const data = JSON.parse(JSON.stringify(investigationDetails))
    if (activeIndex == -1) return

    // pledge signature
    if (key === 'signature') {
      data[activeIndex].signature = value
    }

    // signatures
    if (Object.keys(SignatureKey).includes(key)) {
      data[activeIndex].signatures ??= []
      const existingSignatureIndex = data[activeIndex].signatures.findIndex(
        (item) => item.key === key
      )
      if (value) {
        if (existingSignatureIndex === -1) data[activeIndex].signatures.push({ key, value })
        else data[activeIndex].signatures[existingSignatureIndex].value = value
      } else if (existingSignatureIndex !== -1) {
        data[activeIndex].signatures.splice(existingSignatureIndex, 1)
      }
    }

    setInvestigationDetails(data)
  }

  const goPrevious = () => {
    setViolation({ ...violation, eid, details: investigationDetails })
    setSetup(1)
  }

  const onFinish = async () => {
    const copyInvestigationDetails: Violation['details'] = JSON.parse(
      JSON.stringify(investigationDetails)
    )

    copyInvestigationDetails.forEach((item) => {
      item.signatures = item.signatures?.filter((signature) => signature.value)
    })

    const namesArray = copyInvestigationDetails.reduce((acc, detail) => {
      const hasEmptySignatures = detail.signatures?.length !== signatureList().length
      const hasEmptyQuestion = !detail.questions[0]?.answer || !detail.questions[0]?.question
      if (hasEmptySignatures || !detail.signature || hasEmptyQuestion) {
        acc.push(detail.name)
      }
      return acc
    }, [])

    // const eidArray = copyInvestigationDetails.reduce((acc, detail) => {
    //   const hasEmptySignatures = detail.signatures?.length !== signatureList().length
    //   if (hasEmptySignatures || !detail.signature) acc.push(detail.eid)
    //   return acc
    // }, [])

    if (namesArray.length) {
      modal.info({
        title: t['form.confirm.title'],
        icon: <ExclamationCircleFilled style={{ color: '#FF7D00' }} />,
        className: cs(styles['custom-modal'], lang === 'en-US' ? '' : styles['custom-modal-rtl']),
        closable: true,
        content: `${t['form.confirm.content.continue']} ${namesArray.join(', ')} ${
          t['form.confirm.content.continue1']
        }`,
        okText: t['form.button.ok'],
        okButtonProps: { danger: true },
        // cancelText: t['form.button.cancel'],
        keyboard: false,
        onOk() {
          // setSetup(3)
          // setViolation({
          //   ...violation,
          //   eid,
          //   details: investigationDetails,
          //   undoneSignatureEid: eidArray,
          // })
        },
      })
    } else {
      setSetup(3)
      setViolation({
        ...violation,
        eid,
        details: copyInvestigationDetails,
        undoneSignatureEid: [],
      })
    }
  }

  return (
    <div className={styles['form-details']}>
      <Form layout="vertical" name="details" form={form} onFinish={onFinish}>
        <Row gutter={24}>
          <Col xs={24}>
            <Form.Item label={<FormLabel title={t['form.details.name']} />}>
              <Form.Item
                name="violator"
                rules={[{ required: true, message: t['form.details.name.error'] }]}
              >
                <Select
                  options={violation.details.map((item) => ({
                    value: item.eid,
                    label: item.name,
                  }))}
                  showSearch
                  onChange={changeViolator}
                  optionFilterProp="label"
                  placeholder={t['form.details.name.placeholder']}
                />
              </Form.Item>
            </Form.Item>
          </Col>

          <Col xs={24} className={styles['form-details-investigation']}>
            <Form.Item
              label={<FormLabel title={t['form.details.investigation']} required={false} />}
            >
              <Form.List name="questions">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }, index) => (
                      <Row key={key} className={styles['form-details-investigation-item']}>
                        <Col xs={24}>
                          <Form.Item
                            label={
                              <FormLabel
                                title={`${t['form.details.investigation.question']} ${index + 1}`}
                              />
                            }
                          >
                            <Form.Item
                              {...restField}
                              name={[name, 'question']}
                              rules={[
                                {
                                  required: true,
                                  message: t['form.details.investigation.question.error'],
                                },
                              ]}
                            >
                              <Input
                                maxLength={500}
                                onChange={(e) => changeQuestions(e.target.value, 'question', index)}
                                // placeholder={t['form.details.investigation.question']}
                              />
                            </Form.Item>
                          </Form.Item>
                        </Col>
                        <Col xs={24}>
                          <Form.Item
                            label={
                              <FormLabel
                                title={`${t['form.details.investigation.answer']} ${index + 1}`}
                              />
                            }
                          >
                            <Form.Item
                              {...restField}
                              name={[name, 'answer']}
                              rules={[
                                {
                                  required: true,
                                  message: t['form.details.investigation.answer.error'],
                                },
                              ]}
                            >
                              <TextArea
                                rows={4}
                                showCount
                                maxLength={5000}
                                onChange={(e) => changeQuestions(e.target.value, 'answer', index)}
                                // placeholder={t['form.details.investigation.answer']}
                              />
                            </Form.Item>
                          </Form.Item>
                        </Col>
                        <Col xs={24}>
                          <Form.Item
                            label={
                              <FormLabel
                                title={t['form.details.investigation.attachments']}
                                required={false}
                              />
                            }
                          >
                            <Form.Item
                              {...restField}
                              name={[name, 'attachment']}
                              style={{ marginBottom: 0 }}
                            >
                              <FileUpload
                                fileList={questionsAttachmentValue(index)}
                                type="questions"
                                questionIndex={index}
                              />
                            </Form.Item>
                          </Form.Item>
                        </Col>
                        {fields.length > 1 && (
                          <img
                            src={del}
                            onClick={() => removeQuestion(remove, name)}
                            style={lang === 'en-US' ? { right: '20px' } : { left: '20px' }}
                            className={styles['form-details-investigation-del']}
                            alt="del"
                          />
                        )}
                      </Row>
                    ))}
                    <Form.Item>
                      <span
                        onClick={() => add()}
                        className={styles['form-details-investigation-add']}
                      >
                        {t['form.details.investigation.add']}
                      </span>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form.Item>
          </Col>

          <Col xs={24}>
            <Form.Item label={<FormLabel title={t['form.details.attachments']} required={false} />}>
              <Form.Item
                name="attachment"
                // rules={[{ required: true, message: t['form.details.attachments.error'] }]}
              >
                <FileUpload fileList={attachmentValue()} type="attachment" />
              </Form.Item>
            </Form.Item>
          </Col>

          <Col xs={24}>
            <Form.Item label={<FormLabel title={t['form.details.signatures']} />}>
              <Form.Item
                name="signatures"
                // rules={[{ required: true, message: t['form.details.signatures.error'] }]}
              >
                <div className={styles['form-details-signatures']}>
                  {signatureList().map((item) => {
                    return (
                      <div className={styles['form-details-signatures-item']} key={item}>
                        <div className={styles['form-details-signatures-header']}>
                          <span className={styles['form-details-signatures-title']}>
                            {lang === 'en-US' ? SignatureKey[item].en : SignatureKey[item].ar}
                          </span>
                        </div>
                        <div className={styles['form-details-signatures-body']}>
                          <SignatureCanvas
                            key={signaturesKey}
                            value={signaturesValue(item)}
                            onchange={(value) => changeSignature(value, item)}
                          />
                        </div>
                      </div>
                    )
                  })}
                </div>
              </Form.Item>
            </Form.Item>
          </Col>

          <Col xs={24}>
            <div className={styles['form-details-pledge']}>
              <span className={styles['form-title-h4']}>{t['form.details.pledge']}</span>
              <br />
              <span className={styles['form-details-pledge-title']}>
                {/* {t['form.details.pledge.text']} */}
                <span className={styles['form-details-pledge-text']}>
                  <span>{t['form.details.pledge.text']}</span>
                </span>
                <span className={styles['form-details-pledge-text']}>
                  <span className={styles['form-details-pledge-no']}>
                    1. {t['form.details.pledge.text1']}
                  </span>
                  <span
                    className={styles['form-details-pledge-more']}
                    onClick={() => setIsModalOpen(true)}
                  >
                    {t['form.details.pledge.more']}
                  </span>
                </span>
              </span>
              <Row gutter={24}>
                <Col md={12} xs={24}>
                  <Form.Item label={<FormLabel title={t['form.details.pledge.name']} />}>
                    <Form.Item
                      name="violatorName"
                      rules={[{ required: true, message: t['form.details.pledge.name.error'] }]}
                    >
                      <Input disabled maxLength={500} placeholder={t['form.details.pledge.name']} />
                    </Form.Item>
                  </Form.Item>
                </Col>
                <Col md={12} xs={24}>
                  <Form.Item label={<FormLabel title={t['form.details.pledge.emirates']} />}>
                    <Form.Item
                      name="violatorEmiratesID"
                      rules={[{ required: true, message: t['form.details.pledge.emirates.error'] }]}
                    >
                      <Input
                        disabled
                        maxLength={500}
                        placeholder={t['form.details.pledge.emirates']}
                      />
                    </Form.Item>
                  </Form.Item>
                </Col>
                <Col md={12} xs={24}>
                  <Form.Item label={<FormLabel title={t['form.details.pledge.nationality']} />}>
                    <Form.Item
                      name="nationalityValue"
                      rules={[
                        { required: true, message: t['form.details.pledge.nationality.error'] },
                      ]}
                    >
                      <Input
                        disabled
                        maxLength={500}
                        placeholder={t['form.details.pledge.nationality']}
                      />
                    </Form.Item>
                  </Form.Item>
                </Col>
                <Col md={12} xs={24}>
                  <Form.Item label={<FormLabel title={t['form.details.pledge.phone']} />}>
                    <Form.Item
                      name="mobile"
                      rules={[{ required: true, message: t['form.details.pledge.phone.error'] }]}
                    >
                      <Input
                        disabled
                        maxLength={500}
                        placeholder={t['form.details.pledge.phone']}
                      />
                    </Form.Item>
                  </Form.Item>
                </Col>
                <Col xs={24}>
                  {/* <Form.Item label={<FormLabel title={t['form.details.pledge.signature']} />}> */}
                  <Form.Item label={<FormLabel title={signatureText()} />}>
                    <Form.Item
                      name="signature"
                      style={{ marginBottom: 0 }}
                      // rules={[{ required: true, message: t['form.details.signatures.error'] }]}
                    >
                      <div className={styles['form-details-pledge-signature']}>
                        <div className={styles['form-details-pledge-signature-body']}>
                          <SignatureCanvas
                            key={signaturesKey}
                            value={investigationDetails[activeIndex]?.signature}
                            onchange={(value) => changeSignature(value, 'signature')}
                          />
                        </div>
                      </div>
                    </Form.Item>
                  </Form.Item>
                </Col>
              </Row>
            </div>
          </Col>
        </Row>
      </Form>
      <div className={styles['form-button']}>
        <div className={styles['form-button-left']}>
          <div className={styles['form-button-pre']} onClick={() => cancel()}>
            <span className={styles['button-text']}>{t['form.button.cancel']}</span>
          </div>
          <div className={styles['form-button-pre']} onClick={() => goPrevious()}>
            <img src={arrowPre} className={styles['button-icon']} alt="pre" />
            <span className={styles['button-text']}>{t['form.button.previous']}</span>
          </div>
        </div>
        <div className={styles['form-button-next']} onClick={() => form.submit()}>
          <img src={arrowNext} className={styles['button-icon']} alt="next" />
          <span className={styles['button-text']}>{t['form.button.next']}</span>
        </div>
      </div>

      <UploadFileCom ref={uploadRef} onFile={onFile} />

      <Modal
        title={t['form.details.pledge.title']}
        width={855}
        open={isModalOpen}
        footer={null}
        onCancel={handleCancel}
        className={styles['pledge-modal']}
      >
        <p>
          <span>{t['form.details.pledge.text']}</span>
        </p>
        <p>
          <span>1. </span>
          <span>{t['form.details.pledge.text1']}</span>
        </p>
        <p>
          <span>2. </span>
          <span>{t['form.details.pledge.text2']}</span>
        </p>
        <p>
          <span>3. </span>
          <span>{t['form.details.pledge.text3']}</span>
        </p>
        <p>
          <span>4. </span>
          <span>{t['form.details.pledge.text4']}</span>
        </p>
        <p>
          <span>5. </span>
          <span>{t['form.details.pledge.text5']}</span>
        </p>
        <p>
          <span>6. </span>
          <span>{t['form.details.pledge.text6']}</span>
        </p>
        <p>
          <span>7. </span>
          <span>{t['form.details.pledge.text7']}</span>
        </p>
        <p>
          <span>8. </span>
          <span>{t['form.details.pledge.text8']}</span>
        </p>
        <p>
          <span>9. </span>
          <span>{t['form.details.pledge.text9']}</span>
        </p>
        <p>
          <span>10. </span>
          <span>{t['form.details.pledge.text10']}</span>
        </p>
        <p>
          <span>{t['form.details.pledge.text11']}</span>
        </p>
      </Modal>
    </div>
  )
}

export default InvestigationDetails
